import Vue from "vue";
import VueRouter from "vue-router";
// 引入组件
import Home from "@/views/Home";
import Search from "@/views/Search";
import Login from "@/views/Login";
import Register from "@/views/Register";
import Detail from "@/views/Detail";
import AddCartSuccess from "@/views/AddCartSuccess";
import ShopCart from "@/views/ShopCart";
import Trade from "@/views/Trade";
import Center from "@/views/Center";
import Pay from "@/views/Pay";
import PaySuccess from "@/views/PaySuccess";
import store from "@/store";

Vue.use(VueRouter);

const routes = [
  {
    path: "/home",
    name: "home",
    component: Home,
  },
  {
    path: "/search",
    name: "search",
    component: Search,
  },
  {
    // params参数
    path: "/detail/:id",
    name: "detail",
    component: Detail,
  },
  {
    path: "/login",
    name: "login",
    component: Login,
    meta: {
      isHiddenFooter: true,
    },
  },
  {
    path: "/register",
    name: "register",
    component: Register,
    meta: {
      isHiddenFooter: true,
    },
  },
  {
    path: "/addcart_success",
    name: "addcart_success",
    component: AddCartSuccess,
  },
  {
    path: "/shopcart",
    name: "shopcart",
    component: ShopCart,
  },
  {
    path: "/trade",
    name: "trade",
    component: Trade,
  },
  {
    path: "/center",
    name: "center",
    component: Center,
  },
  {
    path: "/pay",
    name: "pay",
    component: Pay,
  },
  {
    path: "/paysuccess",
    name: "paysuccess",
    component: PaySuccess,
  },
  {
    // * 表示除了以上的其他
    path: "*",
    // 重定向
    redirect: "/home",
  },
];

//  登录用户才能访问：加入购物车成功页面和购物车等页面
//  未登录用户只能访问首页、搜索等页面，访问购物车页面要跳转到登录

// 需要登录才可以进的路由列表
const AUTH_LIST = ["addcart_success", "shopcart"];

const router = new VueRouter({
  // 路由模式
  mode: "history",
  // 滚动行为
  scrollBehavior() {
    return { x: 0, y: 0 };
  },
  base: process.env.BASE_URL,
  // 路由
  routes,
  // 全局路由导航守卫 (对所有的路由组件有效) 路由的生命周期 在路由跳转时触发（中间件机制）
  // 路由全局前置守卫
  beforeEnter: (to, from, next) => {
    // ...
    // 1.登录用户才能访问
    if (AUTH_LIST.includes(to.name)) {
      // 如果有token 会放行 可以访问
      if (store.state.user.token) {
        next();
      } else {
        // 如果没有token 先去登录
        next({
          name: "login",
          query: {
            redirect: to.path, // 记录要去访问等页面
          },
        });
      }
    } else {
      // 2.没有登录也可以访问
      next();
    }
  },
});

export default router;
